<template>
  <div>
    <div v-if="isScanning" id="qr-reader" style="width: 100%; height: 400px;"></div>
    <div v-else>
      <button @click="startScan">开始扫码</button>
    </div>
  </div>
</template>

<script>
import { ref, onUnmounted } from 'vue';
import { Html5QrcodeScanner } from 'html5-qrcode';

export default {
  name: 'QrScanner',
  props: {
    // 扫码成功后的回调函数
    onSuccess: {
      type: Function,
      required: true,
    },
    // 扫码失败后的回调函数
    onError: {
      type: Function,
      required: false,
      default: (errorMessage) => console.log('扫码错误: ', errorMessage),
    },
  },
  setup(props) {
    const isScanning = ref(false);
    let scanner = null;

    const startScan = () => {
      isScanning.value = true;
      scanner = new Html5QrcodeScanner(
        'qr-reader',
        {
          fps: 10, // 扫码帧率
          qrbox: 250, // 扫描框的大小
        },
        false
      );

      scanner.render(onScanSuccess, onScanError);
    };

    const onScanSuccess = (decodedText, decodedResult) => {
      console.log(`扫描成功: ${decodedText}`);
      props.onSuccess(decodedText, decodedResult);  // 触发传入的 onSuccess 回调
      stopScan(); // 扫描成功后停止
    };

    const onScanError = (errorMessage) => {
      props.onError(errorMessage); // 触发传入的 onError 回调
    };

    const stopScan = () => {
      if (scanner) {
        scanner.clear();
        isScanning.value = false;
      }
    };

    onUnmounted(() => {
      if (scanner) {
        scanner.clear();
      }
    });

    return {
      isScanning,
      startScan,
    };
  },
};
</script>

<style scoped>
#qr-reader {
  border: 1px solid #ccc;
  margin: 20px auto;
}
</style>
